//
//  CQUserViewModel.swift
//  weibo
//
//  Created by chengqiang on 16/7/22.
//  Copyright © 2016年 chengqiangBiaodashi. All rights reserved.
//

import UIKit

class CQUserViewModel: NSObject {
    
    //单例
    static let shareduserAccountViewModel:CQUserViewModel=CQUserViewModel()
    var userAccount:CQUserAccont?
    
    
    var userLogin:Bool{
        get {
            return userAccount != nil
        }
    }
    //MARK:-获取用户信息
    func loadUserInfo(completion:(error:NSError?)->()){
        guard let access_token = userAccount!.access_token else{
            print("没有access_token 不发网络请求")
            return
        }
        
        guard let uid = userAccount?.uid else{
            print("没有UID   不发网络请求")
            return
        }
        let urlString = "2/users/show.json"
        let parameters = [
            "access_token":access_token,
            "uid":uid
        ]
        
        //获取用户名字信息
        CQTool.sharedNetworking.GET(urlString, parameters: parameters, progress: nil, success: { (_, responseObject)-> Void in
            let dict = responseObject as? [String: AnyObject]
            let screen_name = dict?["screen_name"] as? String
            let avatar_large = dict?["avatar_large"] as? String
            
            self.userAccount?.screen_name=screen_name
            self.userAccount?.avatar_large=avatar_large
            
            self.saveUserAccount(self.userAccount!)
            completion(error: nil)
        }){
            (_,error)->Void in
            print("请求用户数据失败:\(error)")
        }
    }
    
    
    //账号保存路径
     let userAccountFile = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/userAccount.plist")
    override init() {
        super.init()
        userAccount=loadAccount()
    }
    
     func loadAccessToken(code: String, completion: (error: NSError?) -> Void) {
        let urlString="https://api.weibo.com/oauth2/access_token"
        let paraments=[
                    "client_id": client_id,
                    "client_secret": client_secret,
                    "grant_type": "authorization_code",
                    "code": code,
                    "redirect_uri": redirect_uri]
        CQTool.sharedNetworking.POST(urlString, parameters: paraments, progress: nil, success: { (_, resonpnseObject)-> Void  in
        let dict = resonpnseObject as![String:AnyObject]
        self.userAccount=CQUserAccont(dict: dict)
        print("userAccount==\(self.userAccount)")
        //保存到沙盒中
        NSKeyedArchiver.archiveRootObject(self.userAccount!, toFile: self.userAccountFile)
        }) { (_, error)-> Void in
            completion(error: error)
        }
    }
    private func saveUserAccount(userAccount:CQUserAccont){
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: self.userAccountFile)
    }
    
    private func loadAccount()->CQUserAccont?{
        let account=NSKeyedUnarchiver.unarchiveObjectWithFile(userAccountFile)as?CQUserAccont
        
        if account != nil && account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("没有过期的账号")
            return account
        }
        return nil
    }

    
}
